package com.tskj.leonsu.websocket;

import com.alibaba.fastjson.JSONObject;
import com.tskj.leonsu.service.SystemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author LeonSu
 */
@ServerEndpoint(value = "/ws_mh/{token}", configurator = SpringConfigurator.class)
@Component
public class WebSocket {

    @PostConstruct
    public void init() {
        System.out.println("websocket 加载");
    }

    @Autowired
    private EasyStarSocketUtility easyStarSocketUtility;

    @Autowired
    private SystemService systemService;
    @OnOpen
    public void onOpen(@PathParam("token") String token, Session session) throws IOException, EncodeException {
        if (StringUtils.isEmpty(token)) {
            //回复用户
            easyStarSocketUtility.sendMessage(session, 1, "缺少用户ID");
            return;
        }

        System.out.println("onOpen方法中: token = " + token + " ------ session = " + session);
        System.out.println("当前连接人websocket-SessionId = " + session.getId());
        try {
            if (easyStarSocketUtility.exists(token)) {
                easyStarSocketUtility.update(token, session);
            } else {
                easyStarSocketUtility.add(token, session);
            }
            System.out.println("当前连接数: " + easyStarSocketUtility.size());

//            JSONObject ret = new JSONObject();
//            ret.put("code", 0);
//            ret.put("type", 2);
//            ret.put("data", systemService.getModuleList().toJSONString());
            easyStarSocketUtility.sendMessage(session, 0, "success");
        } catch (Exception e) {
            e.printStackTrace();
            easyStarSocketUtility.sendMessage(session, -1, e.getMessage());
        }
    }

    /**
     * 收到消息时
     *
     * @param message
     * @param session
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println(String.format("收到用户 = {%s} 的消息 = {%s}", session.getId(), message));
        if (message.equalsIgnoreCase("ping")) {
            try {
                easyStarSocketUtility.sendMessage(session, -1, "pong");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭时执行
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println(String.format("连接：{%s} 关闭", easyStarSocketUtility.getToken(session)));
        easyStarSocketUtility.remove(session);
        System.out.println("当前连接数: " + easyStarSocketUtility.size());
    }

    /**
     * 连接错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        easyStarSocketUtility.remove(session);
    }

}
